<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas width="500px" height="500px" id="canvas"></canvas>
	</body>
	<style>
		canvas {
			margin: 0 auto;
			border: 1px solid #000;
			display: block;
		}
	</style>
	<script>
		var canvas = document.querySelector('#canvas'); //获取画布
		var ctx = canvas.getContext('2d'); //获取画布上下文
		
		// 画布宽高
		let w=h=500
		
		function r(num){
			return Math.random()*num
		}
		// 随机属性
		function Ball(){
			this.x=r(500);
			this.y=r(500);
			
			this.r=r(40)+10; //[10,50)
			this.color='#'+parseInt(Math.random()*0xFFFFFF).toString(16);
			this.Xs=r(3)+2;
			this.Ys=r(3)+1;
			
		}
		
		// 定义小球
		Ball.prototype.show = function(){
			// this.run()//记住这个问题
			ctx.beginPath()
			ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
			ctx.fillStyle=this.color;
			ctx.fill()
			ctx.stroke()
		}
		
		// 创建小球数组
		let ballArr=[];
		
		// 创造小球
		for(let i = 0 ; i < 12 ; i ++){
			let ball=new Ball()
			ballArr.push(ball)
			ball.show()
		}
			console.log(ballArr);
		
		// 定义小球碰撞方法
		Ball.prototype.run = function(){
			if(this.x<=this.r||this.x>=w-this.r){
				this.Xs=-this.Xs
			}
			this.x+=this.Xs
			if(this.y-this.r<=0||this.y>=h-this.r){
				this.Ys=-this.Ys
			}
			this.y+=this.Ys
		}
		// 小球运动
		setInterval(function(){
			ctx.clearRect(0,0,w,h);
			for (let i = 0; i < ballArr.length; i++) {
				let ball=ballArr[i]
				ball.run();
				ball.show()
			}
		},50)
		
		
		
	</script>
</html>